#pragma oncre

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "nocopy.hpp"
#include "Log.h"

static int gsockfd = -1;
static const uint16_t glocalport = 8888;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR = 2
};

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t localport = glocalport)
        : _sockfd(gsockfd), _localport(localport)
    {
    }

    void Init()
    {
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCK_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd: %d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport); // htons()将主机序列转换为网路序列
        // local.sin_addr.s_addr = inet_addr(_localip.c_str());
        local.sin_addr.s_addr = INADDR_ANY; // 服务器端进行任意地址绑定

        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }

    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << "client say: " << inbuffer << std::endl;
                std::string echo_string = "[udp_server echo] : ";
                echo_string += inbuffer;

                sendto(_sockfd, echo_string.c_str(), sizeof(echo_string), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip;
    bool _isrunning;
};